package com.example.librarymanagement.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.librarymanagement.dto.menu.MenuDto;
import com.example.librarymanagement.entity.Menu;
import com.example.librarymanagement.entity.User;
import com.example.librarymanagement.exception.BizException;
import com.example.librarymanagement.result.ResultCode;
import com.example.librarymanagement.service.IMenuService;
import com.example.librarymanagement.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * @author fgba
 * @since 2021-05-08
 */
@RestController
@RequestMapping("/sys/menu")
@Api(tags = "菜单模块")
public class MenuController extends BaseController {


    @GetMapping("/nav")
    @ApiOperation("获取导航栏菜单")
    @PreAuthorize("hasAnyRole('admin','normal')")
    public Map<Object, Object> getNavList(Principal principal) {
        User user = userService.getUserByUsername(principal.getName());
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(
                userService.getUserAuthorityInfo(user.getId()), ",");

        return MapUtil.builder().put("perms", authorityInfoArray)
                .put("nav", menuService.getCurrentUserNav()).map();
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    Menu getMenuInfo(@PathVariable Integer id) {
        return menuService.getById(id);
    }

    @GetMapping("/children/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    List<Menu> getChildrenById(@PathVariable Integer id) {
        return menuService.list(new QueryWrapper<Menu>().eq("parent_id", id));
    }

    @GetMapping
    @PreAuthorize("hasAuthority('sys:menu:list')")
    List<Menu> getMenuTreeList() {
        return menuService.getMenuTreeList();
    }

    @PostMapping
    @PreAuthorize("hasAnyAuthority('sys:user:update','sys:user:save')")
    void addOrUpdMenu(@Validated @RequestBody MenuDto menuDto) {
        if (!menuService.addOrUpdMenu(menuDto)) {
            throw new BizException(ResultCode.HANDLE_FAIL);
        }
    }


    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    void delMenu(@PathVariable Integer id) {
        List<Menu> menus = menuService.list(new QueryWrapper<Menu>().eq("parent_id", id));
        if (menus.size() > 0) {
            throw new BizException(ResultCode.SUBMENU_EXIST);
        }
        if (!menuService.delMenu(id)) {
            throw new BizException(ResultCode.HANDLE_FAIL);
        }
    }
}
